const HttpException = require("../exceptions/http_expetion");
const { validateCreateTag } = require("../utils/validate/tag_validate");
const Tag = require("../models/tag");

//创建标签
module.exports.createTag = async (req, res, next) => {
  try {
    //创建标签
    let tag = req.body.tag

    //标签验证
    let { error, validate } = validateCreateTag(tag);
    if (!validate) {
      throw new HttpException(422, "标签不能为空！！！", error);
    }

    //标签存储
    const tagResult = await Tag.create({ name: tag })

    // 返回数据
    res.status(201).json({
      status: 1,
      message: "创建标签成功",
      data: tagResult.dataValues.name
    });

  } catch (err) {
    next(err);
  }
};


//获取标签
module.exports.getTags = async (req, res, next) => {
  try {
    //利用模型查询所有标签
    const tagsAll = await Tag.findAll()

    //标签处理
    const tags = []
    if (tagsAll.length > 0) {
      for (const index of tagsAll) {
        tags.push(index.dataValues.name)
      }
    }

    //响应数据
    res.status(201).json({
      status: 1,
      message: "获取标签成功",
      data: tags
    });

  } catch (err) {
    next(err);
  }
};


